from django.shortcuts import render
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
from rest_framework.permissions import BasePermission
from . import models
import uuid

'''
# 免除csrf认证
@method_decorator(csrf_exempt, name='dispatch')
class OrderView(View):
    def get(self, request, *args, **kwargs):
        
        return Response('...')

    def post(self, request, *args, **kwargs):

        return Response('post')
'''


class MyPermission(BasePermission):
    def has_permission(self, request, view):
        if request.user:
            return True
        return False

    def has_object_permission(self, request, view, obj):
        return False

class MyVersion(object):

    def determine_version(self, request, *args, **kwargs):
        # return request.query_params.get('version')
        return kwargs.get('version', 'v1')


class LoginView(APIView):
    authentication_classes = []
    def post(self, request, *args, **kwargs):
        print(request.data)
        user_obj = models.UserInfo.objects.filter(**request.data).first()
        if not user_obj:
            return Response("登录失败")
        random_string = str(uuid.uuid4())
        user_obj.token = random_string
        user_obj.save()

        return Response(random_string)


from .auth import TokenAuthentication


class OrderView(APIView):
    versioning_class = URLPathVersioning
    permission_classes = [MyPermission,]
    authentication_classes = [TokenAuthentication,]

    def get(self, request, *args, **kwargs):
        print(request.version)
        print(request.versioning_scheme)
        print(request.user)
        print(request.auth)
        if request.user:
            return Response("order")

        return Response("run away")

    def post(self, request, *args, **kwargs):
        return Response("...")


class UserView(APIView):
    authentication_classes = [TokenAuthentication,]

    def get(self, request, *args, **kwargs):
        print(request.user)
        print(request.auth)
        return Response("user")


